import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class NewsDetailsPage extends StatefulWidget {
  final int nid;
  DetailsWeb detailsWeb;

  NewsDetailsPage(
    int this.nid, {
    Key key,
    DetailsWeb this.detailsWeb,
  }) : super(key: key);

  @override
  NewsDetailsPageState createState() {
    return new NewsDetailsPageState();
  }
}

abstract class DetailsWeb {
  Widget createHtmlWidget(String body, List<Widget> pageWidgetContainer);

  Future<bool> canScrollUp();

  Future<bool> canScrollDown();
}

class NewsDetailsPageState extends State<NewsDetailsPage> {
  List<Widget> widgetList = [];

  Widget htmlBodyWidget;

  @override
  void initState() {
    super.initState();
    _getNewsDetails();
    _init();
  }

  @override
  void dispose() {
    super.dispose();
  }

  void _getNewsDetails() async {
    String url = 'http://www.wsrtv.com.cn/services/node/${widget.nid}.json';
    var res = await http.get(url);
    var resJson = json.decode(res.body);
    try {
      List<Widget> tempList = [];
      String title = resJson['title'];

      String titlehtml = '<h1>$title</h1>';
      Padding titleWidget = new Padding(
        padding: EdgeInsets.all(10.0),
        child: new Text(
          title,
          style: TextStyle(
            color: Colors.black,
            fontSize: 20.0,
            fontWeight: FontWeight.bold,
          ),
        ),
      );

      int dateTimestamp = int.parse(resJson['changed']);
      print('time ---- $dateTimestamp');
      var dateTime = DateTime.fromMillisecondsSinceEpoch(dateTimestamp * 1000);
      String date = '${dateTime.year}-${dateTime.month}-${dateTime.day}';
      String count = resJson['totalcount'];

      String dateTimeInfoStr =
          '<p style="margin-top: 5px; margin-bottom: 5px; line-height: 1.75em; color: rgb(0, 0, 0); font-size: 12px;"> $date      浏览量$count</p>';

      Widget newsDateInfo = new IntrinsicHeight(
        child: Padding(
          padding: EdgeInsets.only(left: 10.0, right: 10.0, bottom: 10.0),
          child: new Row(
            mainAxisSize: MainAxisSize.max,
            children: <Widget>[
              IntrinsicWidth(
                child: Text(
                  date,
                  style: TextStyle(color: Colors.black, fontSize: 13.0),
                ),
              ),
              Expanded(
                child: new Padding(
                  padding: EdgeInsets.only(left: 20.0),
                  child: Text(
                    '浏览量$count',
                    style: TextStyle(color: Color(0xff999999), fontSize: 13.0),
                  ),
                ),
              ),
            ],
          ),
        ),
      );

      Widget headerWidget = Container(
        color: Colors.white,
        child: new Column(
          children: <Widget>[titleWidget, newsDateInfo],
        ),
      );
//      tempList.add(headerWidget);

//      try {
//        String videoUrl = resJson['field_news_video_app']['und'][0]['value'];
//        print('videoUrl === $videoUrl');
//        if (videoUrl != null && videoUrl.isNotEmpty) {
//          final playerWidget = new Chewie(
//            new VideoPlayerController.network(
//                'https://flutter.github.io/assets-for-api-docs/videos/butterfly.mp4'
//            ),
//            aspectRatio: 4 / 3,
//            autoPlay: false,
//            looping: false,
//          );
//          tempList.add(playerWidget);
//        }
//      } catch (e) {
//        print('e === ${e.toString()}');
//      }

      String bodyValue = resJson['body']['und'][0]['value'];
      String tempvalue = titlehtml + dateTimeInfoStr + bodyValue;
      Widget bodyText = widget.detailsWeb == null
          ? Container()
          : widget.detailsWeb.createHtmlWidget(tempvalue, widgetList);

      htmlBodyWidget = bodyText;

//      if (bodyText != null) {
//        tempList.add(bodyText);
//      }

      for (int i = 0; i < 120; i++) {
        tempList.add(AppBar(
          title: Text('$i$i$i$i$i$i$i$i$i$i'),
        ));
      }
      setState(() {
        widgetList = tempList;
      });
    } on Exception {}
  }

  ScrollController _scrollController;
  bool _scrollAble = true;
  ScrollPhysics _physics;

  void _init() {
    _scrollController = new ScrollController();
    _physics = NeverScrollableScrollPhysics();
    _scrollController.addListener(() {
      print('_scrollController-------------${_scrollController.toString()}');
      bool scrollAble = false;
      if (scrollAble != _scrollAble) {
        _scrollAble = scrollAble;
        print('---------------------------$_scrollAble');
        setState(() {
          print('setState ----- scrollAbleController------');
//          widgetList.add(AppBar(title: Text('aaaaaaaaaaaaa')));
//          List<Widget> temp = <Widget>[];
//          for (var item in widgetList) {
//            temp.add(item);
//          }
//          widgetList = temp;
        });
      }
    });
  }

  bool canToUp;
  bool canToDown;

  bool moveToUp = true;

  @override
  Widget build(BuildContext context) {
    var physics = _physics;
    return new Scaffold(
      appBar: AppBar(
        title: Text('news details'),
      ),
      body: Listener(
        onPointerMove: (PointerMoveEvent event) {
          print(
              'event web ---- up == ${widget.detailsWeb.canScrollUp()} ---- down =={${widget.detailsWeb.canScrollDown()}');
          moveToUp = event.delta.dy < 0;
        },
        onPointerUp: (PointerUpEvent event) {
          resetScrollState();
          //惯性滑动
          Future.delayed(new Duration(milliseconds: 400), () {
            resetScrollState();
          });
        },
        child: CustomScrollView(
          physics: physics,
          slivers: <Widget>[
            SliverToBoxAdapter(
              child: htmlBodyWidget,
            ),
            SliverList(delegate: new SliverChildListDelegate(widgetList))
          ],
          controller: _scrollController,
        ),
      ),
      floatingActionButton: IconButton(
          icon: Icon(Icons.call),
          color: Colors.yellow,
          onPressed: () {
            setState(() {
              if (_physics is NeverScrollableScrollPhysics) {
                _physics = new ScrollPhysics();
              } else {
                _physics = NeverScrollableScrollPhysics();
              }
            });
          }),
    );
  }

  void resetScrollState() {
    print("moveToUp ---- $moveToUp");
    if (moveToUp) {
      widget.detailsWeb.canScrollDown().then((value) {
        print("moveToUp ---  canScrollDown --- $value");
        print('moveToUp ---- _physics === ${_physics.toString()}');
        if (!value) {
          if ((_physics is NeverScrollableScrollPhysics)) {
            setState(() {
              _physics = ScrollPhysics();
            });
          }
        }
      });
    } else {
      bool isScrollViewTop = _scrollController.offset <= 0;
      print(
          "moveToUp ---- isScrollViewTop = ${isScrollViewTop}");
      if (isScrollViewTop) {
        widget.detailsWeb.canScrollUp().then((value) {
          print("moveToUp ---  canScrollUp --- $value");
          print('moveToUp ---- _physics === ${_physics.toString()}');
          if (value) {
            if (!(_physics is NeverScrollableScrollPhysics)) {
              setState(() {
                _physics = NeverScrollableScrollPhysics();
              });
            }
          }
        });
      }
    }
  }

  buildSlivers(List<Widget> list) {
    if (list != null) {
      Widget sliver = buildChildLayout(context, list);
      return <Widget>[sliver];
    }
    return const <Widget>[];
  }

  Widget buildChildLayout(BuildContext context, List<Widget> children) {
    return SliverList(
        delegate: new SliverChildListDelegate(
      children,
      addAutomaticKeepAlives: true,
      addRepaintBoundaries: true,
      addSemanticIndexes: true,
    ));
  }

  Widget _detailsWidget(BuildContext context, int position) {
    return widgetList[position];
  }
}
